/**
 * @author Nicolas Lusa (lusan@usi.ch)
 */
package ch.usi.inf.pf2.gui.action;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.ImageIcon;

import ch.usi.inf.pf2.circuit.Input;
import ch.usi.inf.pf2.circuit.Value;
import ch.usi.inf.pf2.file.interaction.InstructionWriter;
import ch.usi.inf.pf2.gui.CircuitFrame;
import ch.usi.inf.pf2.gui.Model;
import ch.usi.inf.pf2.time.Schedule;
import ch.usi.inf.pf2.time.SetValueOfInputEvent;

import java.util.ArrayList;


public final class SaveAction extends AbstractAction {
	
	private static final long serialVersionUID = -3414886731730384746L;

	private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));

    private final Model model;
    private final CircuitFrame circuitFrame;
    
    
    public SaveAction(final CircuitFrame circuitFrame, final Model model) {
        this.model = model;
        this.circuitFrame = circuitFrame;
        putValue(NAME, "Save");
        final ImageIcon icon = new ImageIcon(getClass().getResource("../icons/save.png"));
        putValue(SMALL_ICON, icon);
        putValue(SHORT_DESCRIPTION, "Save the current file");

        setEnabled(true);
        

    }
    
    public void actionPerformed(final ActionEvent ev) {
    	if(model.getCircuit() != null) {
            int returnVal = fileChooser.showSaveDialog(circuitFrame);
    
            if(returnVal != JFileChooser.APPROVE_OPTION) {
                return;
            }
            Schedule.resetStep();
    		ArrayList<Input> inputs= model.getCircuit().getInputs();
    		for(Input input : inputs){
    			new SetValueOfInputEvent(Value.UNKNOWN, input, 0);
    		}
    		
            File selectedFile = fileChooser.getSelectedFile();
            InstructionWriter writer = new InstructionWriter(selectedFile.getAbsolutePath(), model.getShapes());
        }
    }
    
}
